import { BrowserWindow, IpcMainInvokeEvent } from 'electron'
import { is } from '@electron-toolkit/utils'
import { join } from 'path'
import windowManager from '../../windowManager'
import eventBus from '../event-bus'

eventBus.on('notify-main', (payload, win) => {
  console.log('[主进程收到消息]', payload)
  win.webContents.send('notify-renderer', { msg: '收到主进程确认' })
})

export default {
  '/set-window-size': async (
    data: { width: number; height: number },
    _event: IpcMainInvokeEvent,
    win: BrowserWindow
  ) => {
    win.setSize(data.width, data.height)
    return { resized: true }
  },
  '/minimize-window': async (_data: any, _event: IpcMainInvokeEvent, win: BrowserWindow) => {
    win.minimize()
    return { minimized: true }
  },
  '/maximize-window': async (_data: any, _event: IpcMainInvokeEvent, win: BrowserWindow) => {
    win.maximize()
    return { maximized: true }
  },
  '/close-window': async (_data: any, _event: IpcMainInvokeEvent, win: BrowserWindow) => {
    if (_data) {
      const target = windowManager.getWindow(_data.name)
      if (target && !target.isDestroyed()) {
        target.close()
        return { closed: true }
      }
      return { closed: false, message: '窗口不存在或已销毁' }
    } else {
      win.close()
      return { closed: true }
    }
  },
  '/is-focused': async (_data: any, _event: IpcMainInvokeEvent, win: BrowserWindow) => {
    return { focused: win.isFocused() }
  },
  '/create-window': async (data: {
    name: string
    url?: string
    width?: number
    height?: number
  }) => {
    const win = windowManager.createWindow(data.name, {
      width: data.width || 800,
      height: data.height || 600,
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'), // 使用预加载脚本
        sandbox: false
      }
    })

    // 获取渲染进程URL
    let baseUrl = ''
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      baseUrl = process.env['ELECTRON_RENDERER_URL']
    } else {
      baseUrl = join(__dirname, '../renderer/index.html')
    }

    await win.loadURL(`${baseUrl}#${data.url}`)
    return { created: true }
  },
  '/get-window-list': async () => {
    return { windows: windowManager.getAllWindows() }
  },
  '/focus-window': async (data: { name: string }) => {
    return { focused: windowManager.focusWindow(data.name) }
  },
  '/close-specific-window': async (data: { name: string }) => {
    return { closed: windowManager.closeWindow(data.name) }
  },
  '/has-window': async (data: { name: string }) => {
    return { exists: windowManager.hasWindow(data.name) }
  },
  '/send-message-to-window': async (data: { name: string; channel: string; payload: any }) => {
    return { sent: windowManager.sendMessageToWindow(data.name, data.channel, data.payload) }
  }
}
